/**
 * Created with IntelliJ IDEA.
 * Description:二分查找
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-08-03  18:43
 */
public class Test4 {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        System.out.println(binarySearch(array, 4));

    }

    public static int binarySearch(int[] array,int key) {
        int left = 0;
        int right = array.length-1;
        while (left <= right) {
            int mid = (left + right)/2;
            if(array[mid] < key) {
                left += 1;
            } else if (key == array[mid]) {
                return mid;
            }else {
                right -= 1;
            }
        }
        return -1;
    }
}
